import 'dart:convert';

import 'package:buy_flutter/common/Application.dart';
import 'package:buy_flutter/common/bloc/loading_bloc.dart';
import 'package:buy_flutter/net/bean/UserInfoBean.dart';
import 'package:buy_flutter/net/net_manager.dart';
import 'package:buy_flutter/net/net_url.dart';
import 'package:buy_flutter/page/main/bloc/main_bloc.dart';
import 'package:buy_flutter/router/router_utils.dart';
import 'package:buy_flutter/router/routes.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'main_view_group.dart';
import 'main_view_right.dart';

class MainView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MainState();
  }
}

class _MainState extends State {
  List<Widget> childrens = [];
  MainBloc _mainBloc = MainBloc();
  GlobalKey<ScaffoldState> _keyScaffoldState = GlobalKey<ScaffoldState>();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    getUserInfo();
  }

  @override
  void initState() {
    super.initState();
    getUserInfo();
  }

  DateTime lastClickDateTime;

  @override
  Widget build(BuildContext context) {
    return BlocProvider<MainBloc>(
      create: (context) => _mainBloc,
      child: WillPopScope(
        onWillPop: () async {
          if (lastClickDateTime == null ||
              DateTime.now().difference(lastClickDateTime) >
                  Duration(seconds: 2)) {
            lastClickDateTime = DateTime.now();
            Fluttertoast.showToast(msg: "連續點擊兩次退出程序");
            return false;
          }
          return true;
        },
        child: Scaffold(
          key: _keyScaffoldState,
          endDrawer: Drawer(
            child: MainRightView(),
          ),
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("assets/main/bg_main_type.png"),
                    fit: BoxFit.fill)),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _headerView(context),
                  MainGroupView(),
                  _bottomView(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _headerView(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Align(
            alignment: Alignment.topRight,
            child: GestureDetector(
              child: BlocBuilder<MainBloc, MainState>(
                builder: (context, state) {
                  String photoStr;
                  try {
                    photoStr = state.userInfoBean.data.photo;
                  } catch (e) {
                    photoStr = "";
                  }
                  return Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 24),
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Color(0x80FFFFFF), width: 3)),
                    child: (photoStr != null && photoStr.isNotEmpty)
                        ? Container(
                            width: 50,
                            height: 50,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: NetworkImage(
                                    "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1950846641,3729028697&fm=26&gp=0.jpg"),
                              ),
                              borderRadius:
                                  BorderRadiusDirectional.circular(25),
                            ),
                          )
                        : Image.asset(
                            "assets/main/ic_default_header.png",
                          ),
                  );
                },
              ),
              onTap: () {
                // getUserInfo();
                _keyScaffoldState.currentState.openEndDrawer();
              },
            ),
          ),
          RichText(
              text: TextSpan(children: [
            TextSpan(
                text: "GA",
                style: TextStyle(
                    color: Color(0xFFB61C31),
                    fontSize: 24,
                    fontWeight: FontWeight.bold)),
            TextSpan(
                text: "PSK",
                style: TextStyle(
                    color: Color(0xFF075A95),
                    fontSize: 24,
                    fontWeight: FontWeight.bold)),
          ])),
          Text("A.I啟蒙學習系統",
              style: TextStyle(
                  color: Color(0xFF58C7B7),
                  fontSize: 24,
                  fontWeight: FontWeight.bold))
        ],
      ),
    );
  }

  Widget _bottomView() {
    return Expanded(
      child: Align(
        alignment: Alignment.bottomCenter,
        child: GestureDetector(
          child: Image.asset("assets/main/ic_main_bottom.png",
              width: double.infinity),
          onTap: () {
            RouterUtils.goToNativePage(Routes.apmApp);
          },
        ),
      ),
    );
  }

  void getUserInfo() async {
    try {
      Response<String> response =
          await NetManager.getInstance().get<String>(NetUrls.get_profile);
      String resStr = response.data;
      print(resStr);
      UserInfoBean userInfoBean = UserInfoBean.fromJson(json.decode(resStr));
      if (userInfoBean != null && userInfoBean.code == 200) {
        print("获取个人信息成功");
        _mainBloc.add(MainUserInfoChanged(userInfoBean));
      } else if (userInfoBean != null && userInfoBean.code == 401) {
        Application.router
            .navigateTo(context, Routes.welcome, clearStack: true);
      }
    } catch (e) {
      print("getUserInfo=====error" + e.toString());
    }
  }
}
